<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" label-position="top" ref="dataFormRef"
      @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-row>
        <el-col :span="11">
          <el-form-item prop="name" :label="$t('dept.name')">
            <el-input v-model="dataForm.name" :placeholder="$t('dept.name')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11" :offset="2">
          <el-form-item prop="parentName" :label="$t('dept.parentName')" class="dept-list">
            <el-popover :width="400" ref="deptListPopover" placement="bottom-start" trigger="click"
              popper-class="popover-pop">
              <template v-slot:reference>
                <el-input v-model="dataForm.parentName" :readonly="true" :placeholder="$t('dept.parentName')">
                  <template v-slot:suffix>
                    <el-icon v-if="user.superAdmin === 1 && dataForm.pid !== '0'"
                      @click.stop="deptListTreeSetDefaultHandle()" class="el-input__icon"><circle-close /></el-icon>
                  </template> </el-input></template>
              <div class="popover-pop-body"><el-tree :data="deptList" :props="{ label: 'name', children: 'children' }"
                  node-key="id" ref="deptListTree" :highlight-current="true" :expand-on-click-node="false" accordion
                  @current-change="deptListTreeCurrentChangeHandle"> </el-tree></div>
            </el-popover>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item prop="type" :label="$t('dept.type')">
            <ren-select v-model="dataForm.type" dict-type="dept_type"></ren-select>
          </el-form-item>
        </el-col>
        <el-col :span="11" :offset="2">
          <el-form-item prop="director" :label="$t('dept.director')">
            <el-select v-model="dataForm.director" :placeholder="$t('choose')" ref="directorRef"
              @change="handleDirectorChange">
              <el-option v-for="item in teacherList" :key="item.id" :label="item.name" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item prop="sort" :label="$t('dept.sort')">
            <el-input-number v-model="dataForm.sort" controls-position="right" :min="0"
              :label="$t('dept.sort')"></el-input-number>
          </el-form-item></el-col>
        <el-col :span="11" :offset="2"></el-col>
      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { IObject } from "@/types/interface";
import { useAppStore } from "@/store";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";

const store = useAppStore();
const { t } = useI18n();

const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);
const dataFormRef = ref();
const deptList = ref([]);
const deptListPopover = ref();
const deptListTree = ref();
const teacherList = ref();

const dataForm = reactive({
  id: "",
  name: "",
  pid: "",
  parentName: "",
  sort: 0,
  type: "",
  delFlag: 0,
  director: "",
  directorMobile: ''
});

const user = computed(() => store.state.user);

const rules = ref({
  name: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  parentName: [{ required: true, message: t("validate.required"), trigger: "change" }],
});


const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  getDeptList().then(() => {
    Promise.all([]).then(() => {
      if (id) {
        getInfo(id);
      } else if (store.state.user.superAdmin === 1) {
        deptListTreeSetDefaultHandle();
      }
    });
  });
};

// 获取部门列表
const getDeptList = () => {
  return baseService.get("/data/class/list").then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    deptList.value = res.data;
  });
};

// 获取部门列表
const getTeacherList = () => {
  return baseService.get("/school/teacher/page?pageSize=1000").then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    teacherList.value = res.data.list;
  });
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get(`/data/class/${id}`).then((res) => {
    Object.assign(dataForm, res.data);

    if (dataForm.pid === "0") {
      return deptListTreeSetDefaultHandle();
    }
    deptListTree.value.setCurrentKey(dataForm.pid);
  });
};

// 上级部门树, 设置默认值
const deptListTreeSetDefaultHandle = () => {
  dataForm.pid = "0";
  dataForm.parentName = t("dept.parentNameDefault");
};

// 上级部门树, 选中
const deptListTreeCurrentChangeHandle = (data: IObject) => {
  dataForm.pid = data.id;
  dataForm.parentName = data.name;
  deptListPopover.value.hide();
};

const directorRef = ref()
// 选择负责人
const handleDirectorChange = () => {
  const obj = teacherList.value.find((v: IObject) => { return v.name === dataForm.director });
  dataForm.directorMobile = obj.mobile;
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    baseService[!dataForm.id ? 'post' : 'put']('/data/class', {
      ...dataForm,
    }).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>

<style lang="less" scoped>
.mod-sys__dept {
  .dept-list {

    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
}
</style>
